package org.neptune.service.rabbit;

import java.util.Date;

import org.neptune.api.entity.CacheBean;
import org.neptune.api.entity.Seckill;
import org.neptune.api.entity.SeckillLog;
import org.neptune.api.entity.SeckillOrderWaitPay;
import org.neptune.common.constant.NeptuneConstant;
import org.neptune.common.enums.LogType;
import org.neptune.common.enums.SeckillStatus;
import org.neptune.common.util.RandomUtils;
import org.neptune.service.dao.SeckillLogMapper;
import org.neptune.service.dao.SeckillOrderWaitPayMapper;
import org.neptune.service.redis.RedisRepository;
import org.neptune.service.redis.RedissonUtil;
import org.neptune.service.service.EsLogService;
import org.neptune.service.util.EsLogBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author lwl
 * @date 2019/8/7 14:43
 */
@Component
@RabbitListener(queues = NeptuneConstant.SECKILL_QUENE_NAME)
public class SeckillConsumer {

	private static final Logger logger = LoggerFactory.getLogger(SeckillConsumer.class);

	@Autowired
	private SeckillLogMapper seckillLogMapper;

	@Autowired
	private SeckillOrderWaitPayMapper seckillOrderWaitPayMapper;

	@Autowired
	private EsLogService esLogService;

	@Autowired
	private RedisRepository redisRepository;

	@RabbitHandler
	public void seckillLogProcess(CacheBean cacheBean) {

		try{
			SeckillLog seckillLog = new SeckillLog();
			seckillLog.setUserId(cacheBean.getUserId());
			seckillLog.setSeckillId(cacheBean.getSeckillId());
			seckillLog.setState(new Byte(SeckillStatus.ORDER_STATUS_VALID.getStatus()));
			seckillLogMapper.insertSelective(seckillLog);

			SeckillOrderWaitPay seckillOrderWaitPay = new SeckillOrderWaitPay();
			seckillOrderWaitPay.setUserId(cacheBean.getUserId());
			seckillOrderWaitPay.setSeckillId(cacheBean.getSeckillId());
			seckillOrderWaitPay.setCreateTime(new Date());
			seckillOrderWaitPayMapper.insert(seckillOrderWaitPay);

			EsLogBean esLogBean = new EsLogBean();
			esLogBean.setId(RandomUtils.createRandomUUID());
			esLogBean.setContent(cacheBean.getUserName() + " seckill goods name: "
					+ getSeckillName(cacheBean.getSeckillId()));
			esLogBean.setCreateTime(new Date());
			esLogBean.setTitle(LogType.SECKILL_LOG.getName());
			esLogBean.setLogType(LogType.SECKILL_LOG.getCode());

			esLogService.addEsLog(esLogBean);
		} catch (Exception e){
			logger.error("seckill log consume error:", e);
		}
	}

	private String getSeckillName(String id) {
		String redisKey = RedissonUtil.getRedisKey(NeptuneConstant.REDIS_SECKILL_GOODS_INFO,
				id);
		Seckill seckill = redisRepository.get(redisKey, Seckill.class);
		if (seckill != null){
			return seckill.getName();
		}
		return "";
	}

}
